import Crypto from '@/utils/crypto.js'
import '@/utils/hmac.js'
import '@/utils/sha1.js'
import {
	Base64
} from '@/utils/base64.js'
//  oss 配置
var uploadFileSize = 1024 * 1024 * 100 // 上传文件的大小限制100m
var policyText = {
	expiration: '3022-01-01T12:00:00.000Z', //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
	conditions: [
		['content-length-range', 0, uploadFileSize], // 设置上传文件的大小限制
	],
}
var policyBase64 = Base64.encode(JSON.stringify(policyText))
var message = policyBase64
var timetamp = new Date().getTime()

function randomString(len) {
	len = len || 32
	var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
	var maxPos = chars.length
	var pwd = ''
	for (let i = 0; i < len; i++) {
		pwd += chars.charAt(Math.floor(Math.random() * maxPos))
	}
	return pwd
}
const getSignature = function(policyBase64, env) {
	const accesskey = env.AccessKeySecret
	const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
		asBytes: true,
	})
	const signature = Crypto.util.bytesToBase64(bytes)
	return signature
}
export default {
	data() {
		return {
			oss_info: '',
		}
	},
	methods: {
		/**
		 * OSS-STS-令牌
		 */
		async getOssStsToken() {
			const res = await this.$api.common.system('getOssStsToken')
			if (res.code === 200) {
				this.oss_info = res.data
			}
		},
		// 文件上传
		async fileUpload(type, path, name, fn) {
			let file_name = ''
			// #ifdef H5
			file_name = name
			// #endif
			// #ifdef MP-WEIXIN||APP-PLUS
			let arr = path.split('/')
			file_name = arr[arr.length - 1]
			// #endif
			console.log(file_name)
			let self = this
			await self.getOssStsToken()
			const {
				AccessKeyId,
				AccessKeySecret,
				SecurityToken,
				bucket,
				domain,
				region
			} = self.oss_info
			let store_as = `${bucket}/${type}/${timetamp}${randomString(5)}.${file_name}`
			const signature = getSignature(policyBase64, self.oss_info) //获取签名
			let oss = {
				key: store_as,
				policy: policyBase64,
				signature: signature,
				OSSAccessKeyId: AccessKeyId,
				'x-oss-security-token': SecurityToken,
				success_action_status: '200',
			}
			uni.showLoading({
				title: '文件上传中',
			})
			uni.uploadFile({
				url: domain,
				filePath: path,
				fileType: type,
				name: 'file',
				formData: {
					...oss,
				},
				success: (res) => {
					console.log('uploadImage success, res is:', res)
					uni.hideLoading()
					uni.showToast({
						title: '上传成功',
						icon: 'success',
						duration: 1000,
					})
					const file_url = `${domain}/${store_as}`
					fn(file_url)
				},
				fail: (err) => {
					console.log('upload fail', err)
					uni.hideLoading()
					uni.showModal({
						content: err.errMsg,
						showCancel: false,
					})
				},
			})
		},
	},
}
